/** 页面公共请求方法(必须是async)
 * @property {getIndexConfig} 获取大首页配置
 * @property {memberInfo} 获取用户信息
 * @property {statisticData} 底部数据统计
 * @property {bindShareFn} 分享绑定关联账号
 * @property {chatTo} 全平台兼容聊天跳转（如果不自动发卡片，不用调这个，直接链接跳走就行）
 * @property {getAdvinfoflowConfig} 获取信息流广告配置
 * mod => 模块名   title  => 标题 callback => 回调方法
 * @property {getIndexConfig} 获取大首页配置
 * @property {getToken} 获取指定用户token
 * @property {dvConfig} H5和小程序广告(重要：需要多少获取多少，不够的话就重新获取，重新获取不等于覆盖之前已经获取的广告)
 * 调用模板请参考资讯首页
 * @property {reGetToken} 重新获取token
 * @property {getoutiaoConfig} 获取抖音配置信息
 * @property {getdefaultCity} 获取默认分站
 */
import $ajax from '../request';
export default {
    async getIndexConfig(func) {
        let cityInfo = uni.getStorageSync('cityInfo')
        this.globalData.cityInfo = cityInfo
        let cityStr = '';
        if (cityInfo && cityInfo.cityid) {
            cityStr = '&cityid=' + cityInfo.cityid
        }
        let result = await $ajax.get({
            url: 'include/ajax.php?service=siteConfig&action=config' + cityStr
        });
        let data = result.data;
        if (data.state == 100) {
            this.globalData.siteConfig = data.info;
            this.globalData.cityNum = data.info.siteCityCount;
            this.globalData.ak = data.info.baiduMapKey_wxmini;
            this.globalData.siteDebug = data.info.siteDebug;
            this.globalData.miniProgramName = data.info.miniProgramName;
            this.globalData.defaultindex = data.info.miniProgramTemplate;
        };
        if (func) { //回调
            func(data)
        };
    },
    async memberInfo(id, fn = function () { }) {
        let data = {
            service: 'member',
            action: 'detail',
            id: id
        };
        let result = await $ajax.post({
            url: this.encodeUrl('include/ajax.php?'),
            data: data
        });
        if (result.data.state == 100) {
            this.globalData.userInfo = result.data.info;
            fn(result.data.info);
        } else {
            console.log('没获取到用户信息')
            if (!this.globalData.checkLogin) {
                this.userInfoError();
            }
        }
        return result.data;
    },
    async statisticData(login = false) {
        if (!this.globalData.userid) { //未登录
            if (login) { //是否启用登录验证，默写页面必须登录才能用，
                this.loginCheck('', true); //登录验证
            }
            return false
        }
        let data = {
            service: 'member',
            action: 'message',
            type: 'tongji',
            im: '1'
        };
        let result = await $ajax.post({
            url: this.encodeUrl("include/ajax.php?"),
            data: data,
        });
        return result
    },
    async bindShareFn(targetUserid) {
        let data = {
            service: 'member',
            action: 'bindFxRelation',
            fromShare: targetUserid
        }
        let result = await $ajax.post({
            url: this.encodeUrl("include/ajax.php?"),
            data: data,
        });
        uni.removeStorageSync('fromShare');
    },
    async chatTo({
        title = '', // 聊天卡片标题
        price = '', //价格
        imgUrl = '', //相当于分享logo
        link = '', //跳转链接
        mod = '', //模块名称
        type = 'link', //一般不用改
        toUserid = '', //聊天对象的userid
    }) {
        let myToken = await this.getToken(this.globalData.userid);
        let itToken = await this.getToken(toUserid);
        let time = Math.round(new Date().getTime() / 1000).toString();
        let msg = {
            mod: mod,
            chatid: toUserid,
            imgUrl: imgUrl,
            link: link,
            title: title,
        }
        if (price) {
            msg['price'] = price;
        }
        let data = {
            content: JSON.stringify(msg),
            contentType: type,
            from: myToken.data.info.token, //自己的token
            fid: this.globalData.userid, // 自己的userid
            to: itToken.data.info.token, //聊天对象的token
            tid: toUserid, //聊天对象的userid
            type: "person",
            time: time
        }
        uni.showLoading({
            title: '正在唤起聊天框...'
        });
        $ajax.post({
            url: this.encodeUrl('include/ajax.php?service=siteConfig&action=sendImChat'),
            data: data
        }).then(res => {
            uni.hideLoading();
            if (res.data.state == 100) {
                if (this.globalData.platForm == 'web' && this.globalData.appBoolean) {
                    let param = {
                        from: this.globalData.userid,
                        to: toUserid,
                    };
                    setupWebViewJavascriptBridge(function (bridge) {
                        bridge.callHandler('invokePrivateChat', param, function (responseData) {
                            console.log(responseData)
                        });
                    });
                } else {
                    let url =
                        `${this.globalData.appConfig.cfg_user_index}/im/chat-${toUserid}.html`;
                    this.linkTo(url)
                }
            } else {
                uni.showToast({
                    icon: "error",
                    title: res.data.info,
                })
            }
        })
    },
    async getAdvinfoflowConfig(mod, title, callback) {
        let result = await $ajax.post({
            url: `include/ajax.php?service=siteConfig&model=${mod}&action=adv&title=${title}`,
        });
        if (result) {
            // callback(res); //原来的 不确定  报错了
            callback(result); //修改后的
        }
    },
    async getToken(userid = '') {
        const _this = this;
        let data = {
            service: 'siteConfig',
            action: 'getImToken',
            userid: userid
        }
        let result = await $ajax.post({
            url: _this.encodeUrl('include/ajax.php?'),
            data: data
        })
        return result;
    },
    async dvConfig({
        module = '',
        config = [] //数组对象，对象内容是title、count(除了count都是必传的)
    }, fn) { //回调函数fn
        if (this.globalData.moduleAdv[module]) { //已经执行过了
            fn();
            return false
        }
        this.globalData.moduleAdv[module] = {};
        let platForm = this.globalData.platForm;
        for (let i = 0; i < config.length; i++) {
            let item = config[i];
            this.globalData.moduleAdv[module][item.page] = {};
            let data = {
                service: 'siteConfig',
                action: 'adv',
                model: module,
                title: item.title
            };
            let result = await $ajax.post({
                url: 'include/ajax.php?',
                data: data
            });
            if (result.data.state == 100) {
                let dataStr = result.data.info.body;
                if (dataStr && dataStr.indexOf('TencentGDT') > -1) { //需要设置流媒体
                    let data_json = JSON.parse(dataStr);
                    if (platForm != 'web') {
                        this.globalData.moduleAdv[module][item.page] = data_json;
                        fn();
                    } else {
                        // 获取h5端端app_id和placement_id,
                        let app_id = data_json['TencentGDT']['h5'].app_id;
                        let placement_id = data_json['TencentGDT']['h5'].placement_id; //广告位id
                        window.TencentGDT = window.TencentGDT || [];
                        // 2. 广告初始化：填写参数值。 具体字段含义详见:《H5SDK 开发者文档》：https://developers.adnet.qq.com/doc/web/js_develop
                        window.TencentGDT.push({
                            app_id: app_id, // {String} - APPID - 必填
                            placement_id: placement_id, // {String} - 广告位ID - 必填
                            type: 'native', // {String} - 原生广告类型 - 必填
                            count: item.count || 10, // {Number} - 拉取广告的数量，默认是3，最高支持10 - 选填，超过 10 条会被限流
                            onComplete: function (res) {
                                if (res && res.constructor === Array) {
                                    let advArr = this.globalData.moduleAdv[module][item.page];
                                    if (advArr.adv) { //已有广告，这个是重新获取的
                                        this.globalData.moduleAdv[module][item.page].adv = [...
                                            advArr.adv, ...res
                                        ];
                                    } else { //没有广告
                                        this.globalData.moduleAdv[module][item.page] = {
                                            placement_id: placement_id, //广告位id
                                            adv: res, //广告信息
                                        };
                                    }
                                    fn();
                                } else {
                                    // 加载广告API，如广告回调无广告，可使用loadAd再次拉取广告
                                    // 注意：拉取广告频率每分钟不要超过20次，否则会被广告接口过滤，影响广告位填充率
                                    setTimeout(function () {
                                        TencentGDT.NATIVE.loadAd(placement_id);
                                    }, 3000);
                                }
                            }
                        });
                    }
                }
            } else if (platForm != 'web') { //无广告，或者出错
                let blankAdv = {
                    "TencentGDT": {
                        "h5": {
                            "app_id": "",
                            "placement_id": ""
                        },
                        "android": {
                            "app_id": "",
                            "placement_id": ""
                        },
                        "wxmini": "",
                        "dymini": ""
                    }
                };
                this.globalData.moduleAdv[module][item.page] = blankAdv;
                fn();
            }
        }
        // 3. H5 SDK接入全局只需运行一次，切必须放在第2步之后
        if (platForm == 'web' && window.TencentGDT) {
            (function () {
                var doc = document,
                    h = doc.getElementsByTagName('head')[0],
                    s = doc.createElement('script');
                s.async = true;
                s.src =
                    '//qzs.gdtimg.com/union/res/union_sdk/page/h5_sdk/i.js';
                h && h.insertBefore(s, h.firstChild);
            })();
        }
    },
    async reGetToken() {
        const that = this;
        let result;
        await refreshToken.unit(uni.getStorageSync('refresh_token'), that.globalData.masterDomain).then((
            res) => {
            result = res;
        });
        let datas = result.data;
        if (datas.state == 100) {
            // console.log('更新成功');
            var access_token = datas.info.access_token;
            var refresh_token = datas.info.refresh_token;

            uni.setStorage({
                key: 'access_token',
                data: access_token
            });
            uni.setStorage({
                key: 'refresh_token',
                data: refresh_token
            });
            var token_expired = Date.parse(new Date()) / 1000 + 7200 -
                20; //两个小时有效期，保险起见，用1小时59分钟40秒
            uni.setStorage({
                key: 'token_expired',
                data: token_expired
            });
            that.globalData.access_token = access_token;
            that.globalData.refresh_token = refresh_token;
            that.globalData.token_expired = token_expired;
        } else {
            //清除缓存数据
            uni.removeStorage({
                key: 'userid'
            });
            uni.removeStorage({
                key: 'access_token'
            });
            uni.removeStorage({
                key: 'refresh_token'
            });
            uni.removeStorage({
                key: 'token_expired'
            });
            that.globalData.userid = null;
            that.globalData.access_token = null;
            that.globalData.refresh_token = null;
            that.globalData.token_expired = null;

            // token过期需要跳转登录页面
            let url;
            if (this.globalData.loginMode == 1) { //H5 关闭了微信原生登录
                url = '/pages/redirect/index?url=' + encodeURIComponent(this.addUrlParam(
                    this.globalData.masterDomain + '/login.html?from=wxmini&wxMiniProgramLogin=1',
                    'forcelogout'));
            } else { //原生
                url = '/pages/login/index?wxMiniProgramLogin=1';
            }
            uni.redirectTo({
                url: url
            })
            return false;
        }
        return result.data;
    },
    async getoutiaoConfig() {
        let result = await $ajax.get({
            url: `include/plugins/20/ajax.php`,
        });
        let data = result.data;
        if (data.state == 100 && typeof data != 'string') {
            this.globalData.dyConfig = data.info;
        } else {
            uni.showToast({
                title: typeof data != 'string' ? data.info : data,
                duration: 5000,
                icon: 'none'
            });
        }
    },
    async getdefaultCity() {
        let result = await $ajax.get({
            url: `include/ajax.php?`,
            data: this.encodeUrl('service=siteConfig&action=getSiteCityInfo')
        });
        let data = result.data;
        let info = data.info;
        if (data.state == 100) {
            this.globalData.cityInfo = info;
            uni.setStorage({
                key: 'cityInfo',
                data: info
            });
            uni.setStorageSync('cityname', info.name);
            uni.setStorageSync('cityid', info.cityid);
        } else {
            //没有默认城市，直接跳到选择城市页面 如果开通了自动定位 则跳转选择城市
            if (this.globalData.appConfig && this.globalData.appConfig.site_city_auto_location == 1) {
                uni.redirectTo({
                    url: '/pages/changeCity/index'
                });
            }
        }
    },

    callPhone(tt, phone, dataset, phoneData) {
        var that = this;
        var phoneTip = null;
        if (typeof phone == 'object') {
            phoneTip = phone.title;
            phone = phone.phone;
        }
        uni.hideLoading();
        //判断是否登录
        var userid = that.globalData.userid;
        if (userid == null || userid == '') {
            that.tologin('/pages/goback');
            return false;
        }
        if (phoneData) {
            //隐藏现有的窗口
            tt.phoneData.showPrivateNumber = 0
        } else {
            phoneData = ''
        }
        //隐私保护通话
        if (that.globalData.appConfig.cfg_privateNumber_state == 1) {
            var module = dataset.module;
            var temp = dataset.temp;
            var aid = dataset.aid;
            var dataPrarm =
                `service=siteConfig&action=createPrivateNumber&module=${module}&temp=${temp}&aid=${aid}${phoneData && (`&phoneData=${encodeURIComponent(JSON.stringify(phoneData))}` || '')}`;
            var urlData = that.encodeUrl(dataPrarm);
            $ajax.post({
                url: 'include/ajax.php?' + urlData,
            }).then(res => {
                var data = res.data;
                if (data.state == 100) {
                    //虚拟号码
                    if (data.info.type == 1) {
                        var countDownTime = data.info.expire_second;
                        tt.phoneData.showPrivateNumber = 1;
                        //显示窗口
                        tt.phoneData.privateNumberCountDown = countDownTime;
                        tt.phoneData.privateNumberFrom = data.info.from;
                        tt.phoneData.privateNumberPhone = data.info.number;
                        tt.phoneData.privateNumberDataSet = dataset;

                        //倒计时
                        if (that.globalData.callPhoneCountDown) {
                            clearInterval(that.globalData.callPhoneCountDown);
                        }
                        that.globalData.callPhoneCountDown = setInterval(function () {
                            countDownTime--;
                            if (!tt.phoneData.showPrivateNumber) {
                                clearInterval(that.callPhoneCountDown);
                                return false;
                            }

                            //更新秒数
                            tt.phoneData.showPrivateNumber = tt.phoneData
                                .showPrivateNumber;
                            tt.hidePrivateNumber = tt.hidePrivateNumber;
                            tt.phoneData.privateNumberCountDown = countDownTime;
                            tt.phoneData.privateNumberFrom = tt.phoneData
                                .privateNumberFrom;
                            tt.phoneData.privateNumberPhone == tt.phoneData
                                .privateNumberPhone;
                            tt.phoneData.privateNumberDataSet = tt.phoneData
                                .privateNumberDataSet;

                            //隐藏窗口
                            if (countDownTime <= 0) {
                                clearInterval(that.globalData.callPhoneCountDown);
                                tt.phoneData.showPrivateNumber = 0
                            }
                        }, 1000);

                        //真实号码
                    } else {
                        if (that.globalData.appBoolean) {
                            window.location.href = 'tel:' + data.info.number
                        } else {
                            uni.makePhoneCall({
                                phoneNumber: (data.info.number).toString(),
                                fail: res => {
                                    console.log(res);
                                }
                            });
                        }
                    }
                } else {
                    uni.showToast({
                        title: data.info,
                        icon: 'none',
                        duration: 2000
                    });
                }
            })
            //普通通话
        } else {
            if (phone) {
                if (this.globalData.appConfig.cfg_payPhoneState && phoneTip) {
                    tt.phoneData.showhasPayNumber = 1;
                    //显示窗口
                    tt.phoneData.privateNumberPhone = phone;
                    tt.phoneData.privateNumberPhoneTip = phoneTip;
                } else {
                    if (that.globalData.appBoolean) {
                        window.location.href = 'tel:' + phone
                    } else {
                        uni.makePhoneCall({
                            phoneNumber: phone,
                            fail: res => {
                                console.log(res);
                            },
                            success: res => {
                                // console.log(res);
                            }
                        });
                    }
                }
            } else {
                tt.onLoad();
            }
        }
    },
}